package org.itzixi.netty.websocket;

import io.netty.channel.Channel;
import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.stream.Collectors;

public class UserChannelCache {


    // 用于多端同时接收消息，允许一个账号多个平台在线，ipad，ios，Mac
    // key:userId  value:用户的多个channel
    private static final Map<String, List<Channel>> multiSession = new HashMap<>(32);

    // key:userId  value:客户端长id
    private static final Map<String, String> userChannelIdMap = new HashMap<>(32);


    public static void putChannelOfUser(String channelId, String userId){
        userChannelIdMap.put(channelId, userId);
    }

    public static String getUserIdByChannelId(String channelId){
        return userChannelIdMap.get(channelId);
    }


    public static void putMultiChannels(String userId, Channel channel){
        List<Channel> channelList = getMultiChannels(userId);
        if (channelList == null)
            channelList = new ArrayList<>();
        channelList.add(channel);
        multiSession.put(userId, channelList);

    }
    public static void removeUselessChannels(String userId, String channelId){
        List<Channel> channelList = getMultiChannels(userId);
        if (CollectionUtils.isEmpty(channelList)) return;

        channelList.removeIf(c -> Objects.equals(channelId, c.id().asLongText()));
        // 重新覆盖
        multiSession.put(userId, channelList);
    }


    public static List<Channel> getMultiChannels(String userId){
        return multiSession.get(userId);
    }


    public static List<Channel> getMyOtherChannel(String userId, String channelId){
        List<Channel> multiChannels = getMultiChannels(userId);
        if (CollectionUtils.isEmpty(multiChannels)) return new ArrayList<>();

//        ArrayList<Channel> myOtherChannelList = new ArrayList<>();
        List<Channel> myOtherChannelList = multiChannels.stream().filter(c -> !Objects.equals(c.id().asLongText(), channelId))
                .collect(Collectors.toList());
        return myOtherChannelList;
    }
}
